<script setup>
import { ref, reactive, onMounted } from 'vue';
import { sensorApi, statementitemApi, statementByIdChange, statementAdd } from '@T2/service/api.ts';
import { ElMessage } from 'element-plus';
import { useIuserInfoStore } from '@T2/store/users.ts';

const iuserInfoStore = useIuserInfoStore();
const { info } = iuserInfoStore;

const { type, content } = defineProps({
  type: {
    type: String,
    validator(value) {
      return ['新增', '编辑'].includes(value);
    },
    required: true,
  },
  content: {
    type: Object,
    required: true,
  },
});
const emits = defineEmits(['close']);

const visible = ref(true);
const checkGroup = ref([]);
const Resd = reactive({
  lists: [],
  search: '',
  
  name: '',
  sensorNode: {},
  table: [],
});
onMounted(() => {
  Resd.lists = [];
  Resd.table = [];
  checkGroup.value = [];
  if (type === '新增') {
    getSensors().then(res => {
      Resd.lists = res;
    });
  } else if (type === '编辑') {
    Resd.name = content.statementName;
    Promise.all([getSensors(), getStatementitem()]).then(res => {
      Resd.lists = res[0];
      res[1].forEach(item => {
        Resd.sensorNode[item.sensor] = item.name;
        
        /* 反选复选框 */
        let sensor = res[0].find(i => i.id === item.sensor);
        if (sensor) {
          checkGroup.value.push(sensor);
        }
        
        /* 创建statementitem对象 */
        let table = {
          id: item.id,
          sensor: item.sensor,
          name: item.name,
          _name: item.sensor_name,
          unit: item.sensor_unit,  //单位
          type: item.type,
        };
        Resd.table.push(table);
      });
    });
  }
  
});
const getSensors = () => {
  return new Promise((resolve, reject) => {
    sensorApi({
      method: 'get',
      params: {
        ordering: '-create_time',
        device__unit: content.unit.id,
        recordcirle__isnull: false,
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}
const getStatementitem = () => {
  return new Promise((resolve, reject) => {
    statementitemApi({
      method: 'get',
      params: {
        statement: content.statement,
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}

/* 变量树操作 */
const searchChange = (value) => {
  if (!value) {
    Resd.lists.forEach(item => {
      item.hide = false;
    });
    return;
  }
  Resd.lists.forEach(item => {
    item.hide = item.name.includes(value) ? false : true;
  });
}
const handleCheckedChange = (value) => {
  /* 当前传入的value:变量对象*/
  Resd.table = [];
  value.forEach(item => {
    if (!Resd.sensorNode[item.id]) {
      Resd.sensorNode[item.id] = item.name;
    }
    /* 创建statementitem对象 */
    let table = {
      id: null,
      sensor: item.id,
      name: Resd.sensorNode[item.id],
      _name: item.name,
      unit: item.unit,  //单位
      type: '曲线图',
    };
    Resd.table.push(table);
  });
}
/* statementitem的table操作 */
const scopeNameChange = (row, value) => {
  Resd.sensorNode[row.sensor] = row.name;
}
/* 弹窗操作 */
const cancleClick = () => {
  emits('close', false);
}
const submitClick = () => {
  if (!Resd.name) {
    ElMessage.error('请先输入卡片名称');
    return;
  }
  let items = [];
  if (type === '新增') {
    items = Resd.table.map(item => {
      return {name: item.name, sensor: item.sensor, type: item.type}
    });
    statementAdd({
      method: 'post',
      data: {
        project: content.project,
        create_user: info.id,
        name: Resd.name,
        uunit: content.unit.id,
        type: '曲线图',
        rtype: '分组',
        items,
      },
    }).then(res => {
      ElMessage.success('创建成功');
      emits('close', true);
    })
  } else if (type === '编辑') {
    items = Resd.table.map(item => {
      return {id: item.id, name: item.name, sensor: item.sensor, type: item.type}
    });
    statementByIdChange({
      method: 'put',
      id: content.statement,
      data: {
        name: Resd.name,
        uunit: content.unit.id,
        items,
      },
    }).then(res => {
      ElMessage.success('编辑成功');
      emits('close', true);
    })
  }
}

</script>

<template>
  <div>
    <el-dialog v-model="visible" :title="type" width="1000px" @close="emits('close', false)">
      <div class="title flex--center">
        <span>卡片名称：</span>
        <el-input v-model="Resd.name" style="width: 180px;"></el-input>
      </div>
      
      <div class="flex" style="margin-bottom: 30px;">
        <div class="left-box flex-column">
          <el-input v-model="Resd.search" placeholder="请输入搜索内容" @input="searchChange">
            <template #suffix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <div class="unit-name ellipsis">{{ content.unit?.name }}</div>
          <el-checkbox-group
            class="sensors-box flex-column scroller"
            v-model="checkGroup"
            :max="8"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-show="!item.hide"
              v-for="item in Resd.lists"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-checkbox-group>
        </div>
        <div class="right-box">
          <el-table
            :data="Resd.table"
            scrollbar-always-on
            :header-cell-style="{backgroundColor: '#fafafa'}"
          >
            <el-table-column type="index" label="序号" align="center" width="65" />
            <el-table-column prop="name" label="表头名称" min-width="180">
              <template #default="scope">
                <el-input v-model="scope.row.name" @input="scopeNameChange(scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="_name" label="数据名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="unit" label="单位" min-width="100" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancleClick()">取 消</el-button>
          <el-button type="primary" @click="submitClick()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-dialog) {
  padding-right: 0;
  padding-left: 0;
  .el-dialog__body,
  .el-dialog__header {
    padding-left: 24px; /* px-to-viewport-ignore */
    padding-right: 24px;/* px-to-viewport-ignore */
  }
  .el-dialog__header {
    border-bottom: 1px solid rgba(0,0,0,0.06);
  }
}
.title {
  margin: 20px 0; /* px-to-viewport-ignore */
  span {
    font-size: 16px; /* px-to-viewport-ignore */
    color: rgba(18,30,52,0.85);
    margin-right: 10px;
  }
}
.left-box {
  border-radius: 2px;
  border: 1px solid rgba(18,30,52,0.15);
  width: 260px; /* px-to-viewport-ignore */
  height: 480px; /* px-to-viewport-ignore */
  padding: 10px; /* px-to-viewport-ignore */
  .unit-name {
    color: #121E34;
    margin: 16px 0 10px; /* px-to-viewport-ignore */
  }
  .sensors-box {
    overflow-x: hidden;
    overflow-y: auto;
    flex: 1;
    .el-checkbox {
      margin: 6px 10px; /* px-to-viewport-ignore */
    }
    :deep(.el-checkbox__label) {
      width: 200px;     /* px-to-viewport-ignore */
      font-size: 12px;  /* px-to-viewport-ignore */
      line-height: 20px;/* px-to-viewport-ignore */
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  @supports (scrollbar-width: auto) {
    .scroller {
      scrollbar-width: thin;
      scrollbar-color: rgba(18,30,52,0.15) transparent;
    }
  }
  @supports selector(::-webkit-scrollbar) {
    .scroller::-webkit-scrollbar {
      width: 4px;
      border-radius: 4px;
    }
    .scroller::-webkit-scrollbar-thumb {
      background-color: rgba(18,30,52,0.15);
      border-radius: 4px;
    }
  }
}
.right-box {
  border-radius: 2px;
  border: 1px solid rgba(18,30,52,0.15);
  width: 700px; /* px-to-viewport-ignore */
  padding: 14px;/* px-to-viewport-ignore */
}
.dialog-footer {
  margin-right: 25px;/* px-to-viewport-ignore */
}

</style>